package com.utc.cards.table.jade.agent.rulesAgent;

import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.Constants;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.HostModel;
import com.utc.cards.model.deck.Deck;
import com.utc.cards.model.game.IRules;
import com.utc.cards.model.player.IPlayer;

public class FirstPlayerBehaviour extends OneShotBehaviour
{
    private static final long serialVersionUID = 6728729092826835695L;
    private static Logger log = LoggerFactory.getLogger(FirstPlayerBehaviour.class);

    private RulesAgent agent;
    private IRules rules;

    public FirstPlayerBehaviour(RulesAgent rulesAgent, HostModel model)
    {
        super(rulesAgent);
        this.agent = rulesAgent;
        this.rules = agent.getModel().getGame().getRules();
    }

    @Override
    public void action()
    {
        log.debug("Searching first player ...");
        Deck hand = agent.getModel().getGame().getDeck();
        List<IPlayer> players = agent.getModel().getGame().getPlayers();

        ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
        IPlayer first_Player = rules.determineFirstPlayer(hand, players);
        msg.setConversationId("first-player");
        msg.addReceiver(new AID(Constants.CARDS_HOST_GAME_AGENT_NAME, AID.ISLOCALNAME));
        try
        {
            msg.setContent(Mapper.getObjectMapper().writeValueAsString(first_Player.getName()));
            agent.send(msg);
        }
        catch (JsonProcessingException e)
        {
            log.error("Error while mapping ");
            e.printStackTrace();
        }
        log.debug("Searching first player DONE");
    }

}
